import React, { createContext, useEffect } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { Button, Divider, Text, useToast, View } from 'native-base';
import { ScrollView, StyleSheet, TouchableOpacity } from 'react-native';
import { FasterImageView } from '@candlefinance/faster-image';
import { CommonStyle } from '../../../common/commonStyle.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { useAsyncEffect, useReactive } from 'ahooks';
import Tools from '../../../utils/Tools.ts';
import LoadingSkeleton from '../../../component/LoadingSkeleton.tsx';
import AdditionalForm from '../component/additionalForm';

interface IProductSubmissionProps {
  navigation: NavigationProp<any, 'productSubmission'>;
  route: RouteProp<{ productSubmission: { data: IGetBtnDefaultGoodsRes; message?: any } }, 'productSubmission'>;
}
interface IState {
  data?: IGetBtnDefaultGoodsRes;
  goodsAdditionalForm: IGoodsAdditionalInfo[][];
  additionalForm: IGoodsAdditionalInfo[][];
  nums: number;
  mapLocation?: any;
  action: number;
  resultAttrData: IGoodsAdditionalInfo[][];
}
export const ProductSubmissionContext = createContext<any>(undefined);
const ProductSubmission: React.FC<IProductSubmissionProps> = ({ navigation, route }) => {
  const state = useReactive<IState>({ nums: 1, goodsAdditionalForm: [], additionalForm: [], action: 0, resultAttrData: [] });
  const toast = useToast();

  useAsyncEffect(async () => {
    if (route.params && route.params.data) {
      state.data = route.params.data;
      await handleProcProdAndAddInfo();
    }
    if (route.params && route.params.message) {
      state.mapLocation = JSON.parse(route.params.message);
    }
  }, [route.params]);

  // 处理产品信息与附加信息
  const handleProcProdAndAddInfo = async () => {
    if (state.data) {
      // 计算产品活动、销售时间
      state.data = { ...state.data };
      // 获得附加信息
      const { attr } = state.data;

      // 组合附加属性数据
      if (attr) {
        if (attr['1']) {
          Object.keys(attr['1']).forEach((key) => {
            state.goodsAdditionalForm.push(attr['1'][key]);
          });
          state.resultAttrData[0] = state.goodsAdditionalForm.flat(1);
        }
        if (attr['2']) {
          state.additionalForm = attr['2'];
          state.resultAttrData[1] = attr['2'][0];
        }
      }
    }
  };

  /**
   * 附加信息组件change
   * @param data
   * @param index
   */
  const handleAdditionalInfoChange = (data: IGoodsAdditionalInfo, index: number) => {
    state.resultAttrData[index] = state.resultAttrData[index].map((item) => (item.attrId === data.attrId ? data : item));
  };

  // 提交
  const handleSubmit = () => {
    const result = state.resultAttrData.flat().filter((item) => item !== null);
    const required = result.find((item) => item.requiredFlag && !item.value);
    if (required) {
      toast.show({ description: `${required.attrName}不能为空` });
      return;
    }

    console.log(JSON.stringify(result, null, 2));
  };

  // 渲染产品信息
  const renderProductInfo = () => {
    const { data } = state;
    if (!data) return;
    const { goods } = data;
    return (
      <View style={styles.card}>
        <View style={styles.productInfo_top}>
          <View style={{ width: 80, height: 80 }} overflow={'hidden'}>
            <FasterImageView style={{ flex: 1 }} source={{ url: goods.mainImg, transitionDuration: 0.3, resizeMode: 'contain', cachePolicy: 'discWithCacheControl', showActivityIndicator: true }} />
          </View>

          <View flex={1} ml={2} justifyContent={'space-between'}>
            <View flexDirection={'row'} justifyContent={'space-between'} alignItems={'center'}>
              <Text>{goods.name}</Text>
              {goods.visitFlag > 0 && (
                <Text fontSize={10} borderWidth={0.5} borderColor={CommonStyle.lightGray} borderRadius={4} paddingX={1}>
                  服务上门
                </Text>
              )}
            </View>
            {goods.introduce && (
              <Text color={CommonStyle.normalGrey} fontSize={11} mt={1}>
                {goods.introduce}
              </Text>
            )}
            {goods.remark && (
              <View flexDirection={'row'} mt={1}>
                <Text color={'white'} fontSize={10} bg={CommonStyle.mainColor} borderRadius={4} paddingX={1} paddingY={0.5}>
                  {goods.remark}
                </Text>
              </View>
            )}
            {determineDiscountDisplay(data) && (
              <View flexDirection={'row'} mt={1}>
                <View borderRadius={2} flexDirection={'row'} alignItems={'center'} paddingX={1} color={'#eb5449'} borderWidth={0.5} borderColor={CommonStyle.price}>
                  <AntDesign name={'tago'} color={CommonStyle.price} />
                  {goods.activeDiscount && (
                    <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
                      {goods.activeDiscount}折,限{goods.active.maxNum}份
                    </Text>
                  )}
                  <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
                    {((goods.salePrice / goods.price) * 10).toFixed(2)}折
                  </Text>
                </View>
              </View>
            )}

            <View justifyContent={'flex-end'} flexDirection={'row'} alignItems={'center'} mt={1}>
              {goods.salePrice > 0 && (
                <View flexDirection={'row'} alignItems={'center'}>
                  <Text fontWeight={'bold'} color={CommonStyle.price}>
                    ¥{goods.activeDiscount ? goods.active.activePrice : goods.salePrice}
                  </Text>
                  <Text ml={2} mt={0.5} fontSize={12} textDecorationLine={'line-through'}>
                    ¥ {goods.price}
                  </Text>
                </View>
              )}
              {soldOutTimeJudgment(data) && (
                <Text paddingX={2} fontSize={13} color={CommonStyle.deepGrey}>
                  {goods.stock === 0 ? '已售罄' : '非可售时间'}
                </Text>
              )}
              {!soldOutTimeJudgment(data) && (
                <View flexDirection={'row'} ml={2}>
                  {state.nums > 0 && (
                    <TouchableOpacity>
                      <Ionicons name={'remove-circle-outline'} size={26} color={CommonStyle.mainColor} />
                    </TouchableOpacity>
                  )}
                  {state.nums > 0 && <Text mx={2}>{state.nums}</Text>}
                  <TouchableOpacity>
                    <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} />
                  </TouchableOpacity>
                </View>
              )}
            </View>
          </View>
        </View>
      </View>
    );
  };

  // 渲染产品附加信息
  const renderGoodAdditionalInfo = () => {
    const { data, goodsAdditionalForm } = state;
    if (!data || !goodsAdditionalForm) return;
    const { goods } = data;
    return (
      <React.Fragment>
        {goodsAdditionalForm.map((item, index) => {
          return (
            <View style={styles.card} mt={4} key={index}>
              <Text fontWeight={'bold'}>{goods.name} - 附加信息</Text>
              {goods.introduce && <Text fontSize={12}>{goods.introduce}</Text>}
              <Divider bg={CommonStyle.borderColor} mt={2} />
              <AdditionalForm formList={item} onChange={(data) => handleAdditionalInfoChange(data, 0)} />
            </View>
          );
        })}
      </React.Fragment>
    );
  };

  // 渲染附加信息
  const renderAdditionalInfo = () => {
    const { data, additionalForm, action } = state;
    if (!data || !additionalForm || additionalForm.length === 0) return;
    return (
      <View style={styles.card} mt={4}>
        <Text fontWeight={'bold'}>附加信息</Text>
        <View flex={1} flexDirection={'row'} my={4}>
          {additionalForm.map((item, index) => {
            return (
              <TouchableOpacity
                style={{ flex: 1 }}
                key={index}
                onPress={() => {
                  state.action = index;
                  state.resultAttrData[1] = state.additionalForm[index];
                }}
              >
                <Text flex={1} textAlign={'center'} color={action === index ? CommonStyle.price : CommonStyle.lightGray} fontWeight={action === index ? 'bold' : ''}>
                  填写方式{index + 1}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>
        <AdditionalForm formList={additionalForm[action]} onChange={(data) => handleAdditionalInfoChange(data, 1)} />
      </View>
    );
  };

  const renderRoot = () => {
    if (state.data) {
      return (
        <React.Fragment>
          <ScrollView contentContainerStyle={styles.container}>
            {renderProductInfo()}
            {renderGoodAdditionalInfo()}
            {renderAdditionalInfo()}
            <View height={20} mt={4} />
          </ScrollView>
          <View width={'100%'} bottom={8} paddingX={4}>
            <Button bg={CommonStyle.mainColor} width={'100%'} borderRadius={8} _pressed={{ bg: CommonStyle.btnSelectMainColor }} onPress={handleSubmit}>
              发送订单
            </Button>
          </View>
        </React.Fragment>
      );
    }
    return <LoadingSkeleton rows={7} />;
  };

  return <ProductSubmissionContext.Provider value={state.mapLocation}>{renderRoot()}</ProductSubmissionContext.Provider>;
};

// 折扣显示判断
const determineDiscountDisplay = (data: IGetBtnDefaultGoodsRes) => {
  const { goods } = data;
  if ((goods.salePrice && goods.salePrice != goods.price) || (goods.salePrice && goods.activeDiscount)) {
    return true;
  }
  return false;
};

// 加减数量显示判断
const soldOutTimeJudgment = (data: IGetBtnDefaultGoodsRes) => {
  const { goods } = data;
  return goods.stock === 0 || goods.saleState !== 2;
};

const styles = StyleSheet.create({
  container: { flexGrow: 1, padding: 16 },
  card: { paddingHorizontal: 8, paddingVertical: 12, backgroundColor: 'white', borderRadius: 8 },
  productInfo_top: { flexDirection: 'row', width: '100%', paddingHorizontal: 4 },
});
export default ProductSubmission;
